# -*- coding: utf-8 -*-

from odoo import http
from odoo.http import request
import json
import logging
import functools

_logger = logging.getLogger(__name__)


def api_response(success=True, data=None, message='', code=200):
    """统一API响应格式"""
    return {
        'code': code if success else 400,
        'success': success,
        'message': message,
        'data': data or {}
    }


def validate_token(func):
    """验证令牌装饰器（用于type='json'路由）"""
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        token = request.httprequest.headers.get('Authorization', '').replace('Bearer ', '')
        
        if not token:
            # type='json'路由直接返回字典，不用make_json_response
            return api_response(False, message='未提供访问令牌', code=401)
        
        user = request.env['wechat.user'].sudo().search([('token', '=', token)], limit=1)
        
        if not user or not user.check_token(token):
            # type='json'路由直接返回字典
            return api_response(False, message='令牌无效或已过期', code=401)
        
        request.wechat_user = user
        return func(*args, **kwargs)
    
    return wrapper


def require_admin(func):
    """要求全局管理员权限装饰器（用于type='json'路由）"""
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        if not hasattr(request, 'wechat_user') or request.wechat_user.role != 'admin':
            # type='json'路由直接返回字典
            return api_response(False, message='需要全局管理员权限', code=403)
        return func(*args, **kwargs)
    
    return wrapper


def check_activity_permission(activity_id):
    """检查活动管理权限"""
    if not hasattr(request, 'wechat_user'):
        return False
    
    activity = request.env['speech.activity'].sudo().browse(activity_id)
    if not activity.exists():
        return False
    
    return activity.can_user_manage(request.wechat_user)


class SpeechManagementController(http.Controller):

    @http.route('/api/v1/ping', type='http', auth='public', methods=['GET'], csrf=False, cors='*')
    def ping(self, **kwargs):
        """健康检查"""
        return request.make_json_response(api_response(True, {'status': 'ok'}, '服务正常'))

